<template>
  <n-card :bordered="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：状态蓝色为启用、灰色为禁用状态。
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="searchParam" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item>
          <n-input v-model:value="searchParam.key" placeholder="输入区域名称查询"
                   clearable/>
        </n-form-item>
        <n-form-item label="区域">
          <n-space>
            <n-select v-model:value="searchParents.province" :options="provinceOption" @update:value="getCityOption"
                      style="width: 160px" filterable
                      placeholder="请选择省份" clearable/>
            <n-select v-model:value="searchParents.city" :options="cityOption" style="width: 160px" filterable
                      placeholder="请选择地区/市" clearable/>
          </n-space>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(searchParam.key=null,searchParam.pId=null,restParentsData())"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list" :columns="columns"
                :row-key="(row:Recordable) => row.id"
                :params="searchParam"
                :action-column="actionColumn"
                list-url="region/t_list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-space>
          <n-button type="success" v-permission="['admin:add']" @click="()=>(addModel=true)">
            <n-icon :size="18">
              <AddSharp/>
            </n-icon>
            添加
          </n-button>
        </n-space>
      </template>
    </data-table>
  </n-card>
  <!--添加授课区域-->
  <n-modal v-model:show="addModel"
           title="添加授课区域" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 580px" @after-leave="">
    <n-form ref="addFormRef" :model="addForm" :rules="addFormRules" require-mark-placement="left"
            label-placement="left" :label-width="80">
      <n-form-item label="上级区域" path="pId">
        <n-space>
          <n-select v-model:value="addForm.province" :options="provinceOption" @update:value="findFormCity" filterable
                    placeholder="请选择省份" clearable/>
          <n-select v-model:value="addForm.city" v-if="addFormCity.length" :options="addFormCity" filterable
                    placeholder="请选择地区/市" clearable/>
        </n-space>
      </n-form-item>
      <n-form-item label="授课区域" path="rId">
        <n-checkbox-group v-model:value="addForm.rId">
          <n-space item-style="display: flex;">
            <template v-for="item in addFormTeachingArea">
              <n-checkbox :value="item.value" :label="item.label"/>
            </template>
          </n-space>
        </n-checkbox-group>
      </n-form-item>
      <n-form-item label="状态" path="status">
        <n-switch :round="false" v-model:value="addForm.status" :checked-value="0" :unchecked-value="1">
          <template #checked>
            正常
          </template>
          <template #unchecked>
            停用
          </template>
        </n-switch>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script setup lang="ts">
import {computed, h, onBeforeMount, reactive, ref, watch} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import DataTable from "@components/DataTable";
import {
  CascaderOption,
  FormInst,
  NPopconfirm,
  NSwitch,
  SelectOption,
  TreeSelectOption,
  useMessage
} from "naive-ui";
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {getRequest, postPutRequest,delRequest} from "@/api/data.ts";
import {AddSharp} from "@vicons/material";
import {permsJudg} from "@/util";

const message = useMessage()
const searchParam = ref<null | string | any>({
  key: null,
  pId: null,
  status: null,
})
const searchParents = ref({
  province: null,
  city: null,
})
const reginData = ref<CascaderOption[]>([])
const provinceOption = ref<SelectOption[]>([]);
const cityOption = ref<SelectOption[]>([]);

//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '区域名称',
    key: 'name',
  }, {
    title: '上级区域',
    key: 'parentName',
    width: 200,
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center',
    render(row: { id: number, status: number }) {
      return h(NSwitch, {
        round: false,
        checkedValue: 0,
        uncheckedValue: 1,
        value: row.status,
        onUpdateValue: function (value) {
          if (permsJudg('region:status:tarea')) { //权限 有权限进行一下操作
            row.status = value;
            postPutRequest('region/update_t_area_status', {
              id: row.id,
              status: value
            }, 'PUT').then((result: ResponseResult) => {
              message.create(result.message, {
                type: result.code === 200 ? 'success' : 'error',
                duration: 1500,
              });
              row.status = result.code === 200 ? value : value ? 0 : 1;
            })
          }
        }
      })
    }
  }, {
    title: '添加时间',
    key: 'createTime',
    width: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width: 70,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前授课区域吗？',
          },
          disabled: !!record.isDisabled,
          permission: ['admin:del']
        },
      ]
    });
  },
});
//添加授课区域
const addModel = ref<boolean>(false);
const handelSubmitLoading = ref<boolean>(false);
const addFormRef = ref<FormInst | null>(null);
const addFormCity = ref<SelectOption[]>([]);
const addFormTeachingArea = ref<SelectOption[] | any[]>([]);
const addForm = ref({
  pId: <number | null>null,
  rId: [],
  province: <number | null>null,
  city: <number | null>null,
  status: 0,
})
const addFormRules = computed(() => {
  return {
    pId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择上级区域'
    },
    rId: {
      type: 'array',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择授课区域',
    }
  }
})
const getCityOption = (value: number | null) => {
  let cityOp = []
  if (value == null) {
    cityOp = []
  } else {
    cityOp = convertChildrenData(value);
  }
  searchParents.value.city = null;
  searchParam.value.pId = value;
  cityOption.value = cityOp;

}
//监听查询条件中的区域
watch(() => searchParents.value.city, (data) => {
  if (data == null) {
    searchParam.value.pId = searchParents.value.province != null ? searchParents.value.province : null;
  } else {
    searchParam.value.pId = data;
  }
})
const restParentsData = () => {
  searchParents.value.province = null;
  searchParents.value.city = null;
  cityOption.value = []
}
const findFormCity = (value: number | null) => {
  let cityOp = []
  if (value == null) {
    cityOp = []
  } else {
    cityOp = convertChildrenData(value);
  }
  addForm.value.city = null;
  addForm.value.pId = value;
  addFormCity.value = cityOp;
  addFormTeachingArea.value = cityOp;
}
watch(() => addForm.value.city, (data) => {
  if (data == null) {
    let childrenData = [], pId: any = null;
    if (addForm.value.province != null) {
      childrenData = convertChildrenData(addForm.value.province);
      pId = addForm.value.province;
    }
    addFormTeachingArea.value = childrenData;
    addForm.value.pId = pId;
  } else {
    addForm.value.pId = data;
    const cityData: CascaderOption | any = reginData.value.find(item => item.value === addForm.value.province);
    addFormTeachingArea.value = cityData.children.find(item => item.value === data).children;
  }
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//删除授课区域
const handleDelete = (record: Recordable) => {
  delRequest('region/del_t_area',record.id).then((result:ResponseResult)=>{
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addFormRef.value?.validate((errors) => {
    if (!errors) {
      // handelSubmitLoading.value = true;
      postPutRequest('region/save_t_area', addForm.value).then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addModel.value = false;
              data_list.value.searchListData();
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
const getRegions = async () => {
  await getRequest('region/get_tree').then((result: ResponseResult) => {
    const {data} = result;
    reginData.value = convertRegin(data);
    provinceOption.value = reginData.value.map((item: any): CascaderOption => ({
      label: item.label,
      value: item.value
    }))
  })
}
const convertChildrenData = (value: number | any) => {
  const data: CascaderOption | any = reginData.value.find(item => item.value === value);
  return data.children.map((item: any): CascaderOption => ({
    label: item.label,
    value: item.value
  }));
}
//处理区域数据
const convertRegin = (data: TreeSelectOption[]) => {
  return data.map((item): CascaderOption => ({
    label: item.label,
    value: item.key,
    ...(item.children && item.children.length > 0 && {children: convertRegin(item.children)}),
  }));
}
onBeforeMount(() => {
  getRegions();
})
</script>

<style scoped lang="scss">

</style>